<?php
namespace app\ux;

use think\Controller;
use think\Db;

class UxDb extends Controller
{

    //定义一个构造方法初始化赋值
    public  function __construct($connect) {

        $this->connect = $connect;
    }
    /**
     * 清空数据库表
     *
     * @param string $tblname 表名
     * @return void
     */
    public function truncateTable($tblname)
    {
        try {

            $sql = "TRUNCATE TABLE " . $tblname;
            Db::connect($this->connect)->execute($sql);

        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 删除数据库表列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public function dropTableColumn($tblname, $field)
    {
        try {

            $sql = "ALTER TABLE " . $tblname . " DROP COLUMN " . $field;
            Db::connect($this->connect)->execute($sql);

        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 为数据库表增加自增列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public function addPK($tblname, $field)
    {
        try {

            $sql = "ALTER TABLE " . $tblname . " ADD " . $field . " INT auto_increment NOT NULL, ADD PRIMARY KEY(" . $field . ")";
            Db::connect($this->connect)->execute($sql);

        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 清空数据库表删除自增主键列之后,重新为表增加自增主键列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public function clearTable($tblname, $field)
    {
        try {

            $this->truncateTable($tblname);
            $this->dropTableColumn($tblname, $field);
            $this->addPK($tblname, $field);

        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }
}
